<template>
    <div ref="terminalRef" class="shell_terminal"></div>
</template>

<script setup lang="ts">
import { Terminal } from '@xterm/xterm'
import '@xterm/xterm/css/xterm.css'
import { FitAddon } from "xterm-addon-fit"
import { WebglAddon } from '@xterm/addon-webgl'
const fitAddon = new FitAddon()
const webglAddon = new WebglAddon()

const terminalRef = ref(null)
const term = ref(null)

const init_term = () => {
    term.value = new Terminal({
        convertEol: true, //启用时，光标将设置为下一行的开头
        disableStdin: false, //是否应禁用输入。
        cursorStyle: "bar", //光标样式
        cursorBlink: true, //光标闪烁
        theme: {
            foreground: 'white', //字体
            background: '#222222', //背景色
            cursor: 'help', //设置光标
        },
        fontFamily: `'Fira Mono', monospace`,
        fontSize: 15,
    });
}


const fitTerm = () => {
    fitAddon.fit()
    console.log("窗口大小改变", window.innerHeight, window.innerWidth)
}

const resizeTerm = function () { // 窗口尺寸变化时，终端尺寸自适应
    const { cols, rows } = term.value
    console.log("同步终端尺寸到设备", cols, rows)
}

const onTermResize = () => {
    window.addEventListener('resize', fitTerm)
}
const removeTermResize = () => {
    window.removeEventListener('resize', fitTerm)
}

onMounted(() => {
    init_term()
    term.value.open(terminalRef.value)
    term.value.loadAddon(fitAddon)
    term.value.loadAddon(webglAddon)
    fitAddon.fit()

    term.value.onData((data) => {
        data = data.replace(/\r/g, "\r\n")
        data = data.replace(/\r\r\n/g, "\r\n")
        data = data.replace(/\n/g, "\r\n")
        data = data.replace(/\r\r\n/g, "\r\n")
        term.value.write(data)
    })
    term.value.onResize(resizeTerm)
    term.value.focus()
    term.value.writeln('Hello from \x1B[1;3;31mxterm.js\x1B[0m $ ')
    onTermResize()
})

onBeforeUnmount(() => {
    removeTermResize()
})

/* 
xterm.js团队维护了以下插件，但任何人都可以构建它们:
​
@xterm/addon-attach:通过websocket连接到运行进程的服务器
@xterm/addon-clipboard:访问浏览器的剪贴板
@xterm/addon-fit:将终端与包含元素匹配
@xterm/addon-image:添加图像支持
@xterm/add -search:添加搜索功能
@xterm/addon-serialize:将终端的缓冲区序列化为VT序列或HTML
@xterm/addon-unicode11:将字符宽度更新为其unicode11值
@xterm/addon-web-links:添加web链接检测和交互
@xterm/addon-webgl:使用画布元素的webgl2上下文渲染xterm.js
*/
</script>

<style scoped>
.shell_terminal {
    height: 100%;
    width: 100%;
    text-align: left;
    text-indent: 1ch;
    overflow: hidden;
}

:deep(.xterm-screen) {
    width: 100% !important;
    height: 100% !important;
}

:deep(.xterm-link-layer) {
    width: 100% !important;
    height: 100% !important;
}
</style>